package com.joolun.cloud.mall.api.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joolun.cloud.common.core.constant.CacheConstants;
import com.joolun.cloud.common.core.constant.CommonConstants;
import com.joolun.cloud.common.core.constant.SecurityConstants;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.common.sms.config.SmsTemplateProperties;
import com.joolun.cloud.common.sms.util.SmsUtils;
import com.joolun.cloud.mall.api.mapper.UserInfoMapper;
import com.joolun.cloud.mall.api.service.PhoneService;
import com.joolun.cloud.mall.common.constant.MyReturnCode;
import com.joolun.cloud.mall.common.entity.UserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class PhoneServiceImpl implements PhoneService {
	private final UserInfoMapper userInfoMapper;
	private final RedisTemplate redisTemplate;
	private final SmsUtils smsUtils;
	private final SmsTemplateProperties smsTemplateProperties;


	/**
	 * 发送手机验证码
	 *
	 * @param phone
	 * @param type
	 * @return code
	 */
	@Override
	public R<Boolean> sendSmsCode(String phone, String type) throws ClientException {
		String signName = null;
		String templateCode = null;
		if(CommonConstants.PHONE_CODE_1.equals(type)){//登录
			signName = smsTemplateProperties.getSignName1();
			templateCode = smsTemplateProperties.getTemplateCode1();
		}else if(CommonConstants.PHONE_CODE_2.equals(type)){//注册、修改手机号码
			//判断手机号是否已经注册
			UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>query().lambda()
					.eq(UserInfo::getPhone, phone));
			if (userInfo != null) {
				log.info("手机号已被注册:{}", phone);
				return R.failed(Boolean.FALSE, "该手机号已被其他账号绑定");
			}
			signName = smsTemplateProperties.getSignName2();
			templateCode = smsTemplateProperties.getTemplateCode2();
		}else if(CommonConstants.PHONE_CODE_4.equals(type)){//重置密码
			signName = smsTemplateProperties.getSignName2();
			templateCode = smsTemplateProperties.getTemplateCode2();
		}

		String key = CacheConstants.VER_CODE_DEFAULT + ":" + phone;
		Long seconds = redisTemplate.opsForValue().getOperations().getExpire(key);

		if (seconds > 240) {
			log.info("验证码发送过频繁:{}", phone);
			return R.failed(MyReturnCode.ERR_70008.getCode(), MyReturnCode.ERR_70008.getMsg());
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		log.debug("手机号生成验证码成功:{},{}", phone, code);
		smsUtils.sendSms(signName, phone, templateCode, "{\"code\":\""+code+"\"}");
		redisTemplate.opsForValue().set(key, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		return R.ok();
	}
}
